#!/usr/bin/perl -w

use strict;

use Getopt::Std;
use CIF::WebAPI::APIKey;
use Text::Table;
use Data::Dumper;

my %opts;
getopt('e:k:u:', \%opts);
die(usage()) if($opts{'h'});
my $user = $opts{'u'} || die(usage()) unless($opts{'k'});
my $access = $opts{'e'};

sub usage {
    return <<EOF;
Usage: perl $0 -u joe\@example.com
    -h  --help:     this meessage
    -e  --enable:   enable access to specific section (infrastructure,domains,malware,etc... default: all)
    -r  --revoke:   revoke a key
    -w  --write:    enable write access
    -a  --add:      add key
    -d  --delete:   delete key
    -k  --key:      apikey

Examples:
    \$> perl $0 -u joe\@example.com
    \$> perl $0 -u joe\@example.com -a
    \$> perl $0 -d -k 96818121-f1b6-482e-8851-8fb49cb2f6c0
    \$> perl $0 -u joe\@example.com -e infrastructure -a
    \$> perl $0 -k 96818121-f1b6-482e-8851-8fb49cb2f6c0 -w
    \$> perl $0 -k 96818121-f1b6-482e-8851-8fb49cb2f6c0 -r

EOF
}

if(exists($opts{'a'})){
    die(usage()) unless($user);
    CIF::WebAPI::APIKey->genkey(
        userid  => $user,
        access  => $access,
        write   => $opts{'w'},
        revoked => $opts{'r'},
        parentid => $opts{'p'}
    );
} elsif($opts{'r'} || $opts{'w'}) {
    die(usage()) unless($opts{'k'});
    my @r = CIF::WebAPI::APIKey->search(apikey => $opts{'k'});
    if($#r > -1){
        foreach (@r){
            if($opts{'r'}){
                my $val = 0;
                $val = 1 unless($_->revoked());
                $_->revoked($val);
            }
            if($opts{'w'}){
                my $val = 0;
                $val = 1 unless($_->write());
                $_->write($val);
            }
            $_->update();
        }
    }
}

if(exists($opts{'d'})){
    die(usage()) unless($opts{'k'} || $opts{'userid'});
    my @recs = CIF::WebAPI::APIKey->search(apikey => $opts{'k'}, userid => $user, access => $access);
    foreach (@recs){
        $_->delete();
    }
}

unless($user){
    my @r = CIF::WebAPI::APIKey->search(apikey => $opts{'k'});
    $user = $r[0]->userid();
}
my @recs = CIF::WebAPI::APIKey->search(userid => $user, { order_by => 'created DESC' });
if($#recs > -1){
    my $t = Text::Table->new('id','key','access','write','revoked','created');
    foreach (@recs){
        $t->load([$_->id(),$_->apikey(),$_->access(),$_->write(),$_->revoked(),$_->created()]);
    }
    print $t;
} else {
    die('you have no api keys');
}
